package com.itheima.interceptors;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @outhor
 * @date 2020/2/6 20:47
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;


    /**
     *在我们的controller方法之前执行，preHandle返回true就继续执行controller方法，返回false就不继续执行了
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //1、根据token去redis查询用户信息
        String token = request.getHeader("token");
        if (token==null){
            //告诉客户端要跳转到登录页面
            noLogin(response);
            return false;
        }
        //2、如果没有查询到那就需要跳转到登录页面(前后端分离后端无法跳转页面,反馈JOSN数据给前端处理)
        String memberJson = redisUtil.get(token);
        if (memberJson==null||memberJson==""){
            //告诉客户端要跳转到登录页面
            noLogin(response);
            return false;
        }
        //3、如果查询到了代表已经登录
        return true;
    }

    private void noLogin(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");//告诉客户端我现在写的是一段json
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(new Result(true,401,"请登录")));
        writer.close();
    }
}
